package xiaye.crawler.core.impl;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;

public class HttpFetcher {
	HttpClient httpClient;
	
	public HttpFetcher(){
		HttpParams params = createHttpParams();
		SchemeRegistry schemeRegistry = createSchemeRegistry();
        ClientConnectionManager connManager = new ThreadSafeClientConnManager(params, schemeRegistry);  
        httpClient = new DefaultHttpClient(connManager, params); 
	}

	public HttpResponse fetch(HttpUriRequest request, HttpContext context) throws ClientProtocolException, IOException{
		return httpClient.execute(request, context);
	}
	
	private HttpParams createHttpParams() {
        HttpParams params = new BasicHttpParams();      
        ConnManagerParams.setMaxTotalConnections(params, 100);  
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		params.setParameter("http.useragent", "Mozzila");
		return params;
	}

	private SchemeRegistry createSchemeRegistry() {
        SchemeRegistry schemeRegistry = new SchemeRegistry();  
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));  
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); 
        return schemeRegistry;
	}
	
}
